﻿using Microsoft.VisualBasic;
using Newtonsoft.Json;
using System;
using System.Text;
using System.Windows.Forms;

namespace minidwm
{
    public partial class IncreaseForm : Form
    {

        string strHour = DateTime.Now.TimeOfDay.Hours.ToString();
        string strMouit = DateTime.Now.TimeOfDay.Minutes.ToString();
        string strSecon = DateTime.Now.TimeOfDay.Seconds.ToString();
        DateTime statrTime = DateTime.Now;
        DateTime tipTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 14:50:00"));
        public int intHour, intMouit, intSecon;
        public IncreaseForm()
        {
            InitializeComponent();
        }

        private void btn_Show_Click(object sender, EventArgs e)
        {
            if (this.timer_Show.Enabled != true)
            {
                this.btn_Show.Text = "取消";
                this.timer_Show.Enabled = true;
                statrTime = DateTime.Now;
            }
            else if (this.timer_Show.Enabled != false)
            {
                this.btn_Show.Text = "启动";
                this.timer_Show.Enabled = false;
                statrTime = DateTime.Now;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SetConfig_Click(object sender, EventArgs e)
        {
            this.Hide();
            Formshutdown formshutdown = new Formshutdown();
            formshutdown.Show();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_Show_Tick(object sender, EventArgs e)
        {
            DateTime get_time1 = Convert.ToDateTime(DateTime.Now.ToString());
            //判断是否是周末，或者是15点以后
            if (get_time1.Hour >= 15 || get_time1.DayOfWeek == DayOfWeek.Saturday || get_time1.DayOfWeek == DayOfWeek.Sunday)
            {
                this.btn_Show_Click(sender, e);
                MessageBox.Show("已经停市了！");
                return;
            }
            //判断是否是数字
            Int32.TryParse(tbtime.Text.Trim().ToString(), out int times);
            DateTime sta_ontime1 = statrTime;
            //计算时间差
            long dat = DateAndTime.DateDiff("s", get_time1, sta_ontime1, FirstDayOfWeek.Sunday, FirstWeekOfYear.FirstFourDays);
            if (dat == 0)
            {
                try
                {
                    this.SetStockInfo();
                    statrTime = statrTime.AddMinutes(times);
                }
                catch
                {
                    MessageBox.Show("请求异常");
                }
            }
        }

        /// <summary>
        /// 设置基金数据
        /// </summary>
        public void SetInfo()
        {
            var url = string.Format($"http://fundgz.1234567.com.cn/js/{this.tb_inpuCode.Text}.js");
            long time = DateToTicks(DateTime.Now);
            var postdate = string.Format($"?rt={time}");
            var result = this.RequestUrl(url, postdate, "GET");
            result = result.Replace("jsonpgz(", "");
            result = result.Replace(");", "");
            var apidocResult = JsonConvert.DeserializeObject<Jsonpgz>(result, new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });
            this.tb_Code.Text = apidocResult.fundcode;
            this.tb_jzgs.Text = apidocResult.gsz;
            this.tb_name.Text = apidocResult.name;
            this.tb_Increase.Text = apidocResult.gszzl;
            this.lb_time.Text = apidocResult.gztime;
            var increase = Convert.ToDecimal(apidocResult.gszzl);
            if (increase > 0)
            {
                this.tb_Increase.BackColor = System.Drawing.Color.Red;
                if (increase > 2)
                {
                    DateTime get_time1 = DateTime.Now;
                    DateTime sta_ontime1 = tipTime;
                    long dat = DateAndTime.DateDiff("s", get_time1, sta_ontime1, FirstDayOfWeek.Sunday, FirstWeekOfYear.FirstFourDays);
                    if (dat <= 0)
                    {
                        // 设置提示控件可见
                        this.noIcon.Visible = true;
                        // 显示气泡提示，时间为1秒，内容为当前时间，图标为消息图标
                        this.noIcon.ShowBalloonTip(10000, "基金涨了", $"涨了{increase}%", ToolTipIcon.Info);
                        tipTime = tipTime.AddMinutes(5); //增加5分钟   
                    }
                }
            }
            else if (increase < 0)
            {

                if (increase <= 0)
                {
                    DateTime get_time1 = DateTime.Now;
                    DateTime sta_ontime1 = tipTime;
                    long dat = DateAndTime.DateDiff("s", get_time1, sta_ontime1, FirstDayOfWeek.Sunday, FirstWeekOfYear.FirstFourDays);
                    if (dat <= 0)
                    {
                        // 设置提示控件可见
                        this.noIcon.Visible = true;
                        // 显示气泡提示，时间为1秒，内容为当前时间，图标为消息图标
                        this.noIcon.ShowBalloonTip(10000, "基金跌了：", $"跌了{increase}%准备买入", ToolTipIcon.Info);
                        tipTime = tipTime.AddMinutes(5); //增加5分钟
                    }
                }
                this.tb_Increase.BackColor = System.Drawing.Color.Green;
            }
            this.tb_dwjz.Text = apidocResult.dwjz;
        }
        /// <summary>
        /// 设置股票信息
        /// </summary>
        public void SetStockInfo()
        {
            tipTime = Convert.ToDateTime(DateTime.Now);
            //处理股票信息
            var stockCode = this.tb_inpuCode.Text;
            if (string.IsNullOrEmpty(stockCode))
            {
                MessageBox.Show("请输入股票点");
                return;
            }
            else if (stockCode.StartsWith("6") || stockCode.StartsWith("5"))
            {
                stockCode = "1." + stockCode;
            }
            else if (stockCode.StartsWith("0") || stockCode.StartsWith("3"))
            {
                stockCode = "0." + stockCode;
            }
            var url = $"https://push2.eastmoney.com/api/qt/stock/get?secid={stockCode}&fields=f57,f58,f42,f43,f44,f45,f46,f60";
            var result = HttpHepler.HttpGet(url, Encoding.UTF8);
            var resultData = JsonConvert.DeserializeObject<StockResult>(result, new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });
            if (resultData.Data == null)
            {
                MessageBox.Show("没有获取到数据");
                return;
            }
            this.lb_time.Text = DateTime.Now.ToString();
            //股票名称
            this.label3.Text = "股票名称:";
            //股票代码
            this.label5.Text = "股票代码:";
            //涨幅情况
            this.label1.Text = "涨幅情况:";
            //最新价格
            this.label2.Text = "最新价格:";
            //最高价格
            this.label4.Text = "最高价格:";
            //最新价格
            var nowPice = ((decimal)resultData.Data.F43 / 100);
            //最高价格
            var maxPice = ((decimal)resultData.Data.F44 / 100);
            //最低价格
            var minPice = ((decimal)resultData.Data.F45 / 100);
            //今开价格
            var todayPice = ((decimal)resultData.Data.F46 / 100);
            //昨天收盘价
            var yesterdayPic = ((decimal)resultData.Data.F60 / 100);
            var name = resultData.Data.F58;
            var code = resultData.Data.F57;
            //差价
            var difference = nowPice - yesterdayPic;
            /*
             涨跌幅百分比=((当前价格−昨日收盘价)/昨日收盘价)×100%
             */
            //今天开盘价的百分百
            var todayIncrease = (decimal)(difference / yesterdayPic) * 10;
            var increase = Math.Round(todayIncrease, 2) * 10;
            //股票名称
            this.tb_name.Text = name;
            //股票代码
            this.tb_Code.Text = code;
            //涨幅情况
            this.tb_Increase.Text = (increase).ToString() + "%";
            //最新价格
            this.tb_jzgs.Text = nowPice.ToString();
            //最高价格
            this.tb_dwjz.Text = maxPice.ToString();

            if (increase > 0)
            {
                this.tb_Increase.BackColor = System.Drawing.Color.Red;
                //大于3个点
                if (increase > 3)
                {
                    DateTime get_time1 = DateTime.Now;
                    DateTime sta_ontime1 = tipTime;
                    long dat = DateAndTime.DateDiff("s", get_time1, sta_ontime1, FirstDayOfWeek.Sunday, FirstWeekOfYear.FirstFourDays);
                    if (dat <= 0)
                    {
                        // 设置提示控件可见
                        this.noIcon.Visible = true;
                        // 显示气泡提示，时间为1秒，内容为当前时间，图标为消息图标
                        this.noIcon.ShowBalloonTip(10000, "涨了", $"涨了{increase}%，可以考虑卖出", ToolTipIcon.Info);
                        tipTime = tipTime.AddMinutes(1); //增加5分钟   
                    }
                }
            }
            else if (increase < 0)
            {
                //小于3个点
                if (increase <= -3)
                {
                    DateTime get_time1 = DateTime.Now;
                    DateTime sta_ontime1 = tipTime;
                    long dat = DateAndTime.DateDiff("s", get_time1, sta_ontime1, FirstDayOfWeek.Sunday, FirstWeekOfYear.FirstFourDays);
                    if (dat <= 0)
                    {
                        // 设置提示控件可见
                        this.noIcon.Visible = true;
                        // 显示气泡提示，时间为1秒，内容为当前时间，图标为消息图标
                        this.noIcon.ShowBalloonTip(10000, "跌了：", $"跌了{increase}%准备买入", ToolTipIcon.Info);
                        tipTime = tipTime.AddMinutes(1); //增加5分钟
                    }
                }
                this.tb_Increase.BackColor = System.Drawing.Color.Green;
            }
        }

        /// <summary>
        /// 接口请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="postdata">传递内容</param>
        /// <returns>返回结果</returns>
        private string RequestUrl(string url, string postdata, string method = "POST", string contentType = "application/x-javascript")
        {
            HttpHepler httpHepler = new HttpHepler();
            HttpModel.HttpItem httpItem = new HttpModel.HttpItem
            {
                Method = method,
                Postdata = postdata,
                ContentType = "application/x-javascript",
                URL = url
            };
            var result = httpHepler.GetHtml(httpItem);
            return result.Html;
        }

        /// <summary>
        /// DateTime类型转换为时间戳(毫秒值)
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public long DateToTicks(DateTime? time)
        {
            return ((time.HasValue ? time.Value.Ticks : DateTime.Parse("1990-01-01").Ticks) - 621355968000000000) / 10000;
        }

        /// <summary>
        /// 时间戳(毫秒值)String转换为DateTime类型转换
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public DateTime TicksToDate(string time)
        {
            return new DateTime((Convert.ToInt64(time) * 10000) + 621355968000000000);
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="data">需要反序列化数据</param>
        /// <returns>返回反序列化数据</returns>
        public static string SerializeObject(object data)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            return JsonConvert.SerializeObject(data, settings);
        }



        /// <summary>
        /// 返回值
        /// </summary>
        public class RequestData
        {
            public Jsonpgz Jsonpgz { get; set; }
        }
        /// <summary>
        /// 返回参数
        /// </summary>
        public class Jsonpgz
        {

            /// <summary>
            /// 编码
            /// </summary>
            public string fundcode { get; set; }
            /// <summary>
            /// 编码
            /// </summary>
            public string name { get; set; }
            /// <summary>
            /// 时间
            /// </summary>
            public string jzrq { get; set; }
            /// <summary>
            /// 单位净值（昨日
            /// </summary>
            public string dwjz { get; set; }
            /// <summary>
            /// 单位净值 （现在
            /// </summary>
            public string gsz { get; set; }
            /// <summary>
            /// 估值涨幅
            /// </summary>
            public string gszzl { get; set; }
            /// <summary>
            /// 刷新时间
            /// </summary>
            public string gztime { get; set; }
        }


        /// <summary>
        /// 股票返回值
        /// </summary>
        public class StockResult
        {

            /// <summary>
            /// 
            /// </summary>
            public int rc { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int rt { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public long svt { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int lt { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int full { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string dlmkts { get; set; }
            /// <summary>
            /// 返回数据信息
            /// </summary>
            public StockData Data { get; set; }
        }

        /// <summary>
        /// 股票信息数据
        /// </summary>
        public class StockData
        {
            /// <summary>
            /// 最新价格
            /// </summary>
            public int F43 { get; set; }
            /// <summary>
            /// 最高价格
            /// </summary>
            public int F44 { get; set; }
            /// <summary>
            /// 最低价格
            /// </summary>
            public int F45 { get; set; }
            /// <summary>
            /// 今开价格
            /// </summary>
            public int F46 { get; set; }
            /// <summary>
            /// 股票代码
            /// </summary>
            public string F57 { get; set; }
            /// <summary>
            /// 股票名称
            /// </summary>
            public string F58 { get; set; }
            /// <summary>
            /// 昨日收盘
            /// </summary>
            public int F60 { get; set; }
        }
    }
}
